package com.godyao.mall.gateway.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.*;

/***
* @author godyao
* @description Swagger配置
* @date 2022/4/9 15:12
*/
@Component
@Primary
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {
    private static final String SWAGGER2Url = "/v2/api-docs";

    /**
     * 路由网关
     */
    private final RouteLocator routeLocator;

    @Value("${spring.application.name}")
    private String self;

    public GatewaySwaggerResourcesProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    /***
    * @author godyao
    * @description 让swagger能够找到对应的服务
    * @Param
    * @return java.util.List<springfox.documentation.swagger.web.SwaggerResource>
    * @date 2022/4/9 14:49
    */
    @Override
    public List<SwaggerResource> get() {
        final List<SwaggerResource> resources = new ArrayList<>();
        final List<String> routeHosts = new ArrayList<>();
        // 获取所有可用的host：serviceId
        routeLocator.getRoutes().filter(route -> route.getUri() != null)
                .filter(route -> !self.equals(route.getUri().getHost()))
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));

        // 记录已经添加过的server
        final Set<String> set = new HashSet<>();
        routeHosts.forEach(s -> {
            // 拼接url
            String url = "/" + s.toLowerCase(Locale.ROOT) + SWAGGER2Url;
            if (! set.contains(url)) {
                set.add(url);
                final SwaggerResource swaggerResource = new SwaggerResource();
                swaggerResource.setUrl(url);
                swaggerResource.setName(s);
                resources.add(swaggerResource);
            }
        });
        return resources;
    }
}
